'use strict'

const { Service } = require('ee-core')
const fs = require('fs-extra')
const path = require('path')
/**
 * 示例服务（service层为单例）
 * @class
 */
class FsService extends Service {

    constructor(ctx) {
        super(ctx)
    }

    /**
     * test
     */
    async fsSearch (args) {
        let searchPath = args.path
        const filesInA = getFilesRecursively(searchPath)
        // 创建文件路径映射
        const filePathMap = createFilePathMap(filesInA, searchPath)
        return {
            list: filesInA,
            lsitMap: filePathMap,
            total: filesInA.length
        }
    }
    async fsReplace (args) {
        const searchResult = await this.fsSearch(args)
        const { lsitMap } = searchResult
        const replaceData = replaceFilesInDirectory(args.path2, lsitMap)
        const moveFiles = moveFilesIfNotExist(args.path, args.path2)
        return {
            replaceFiles: replaceData,
            moveFiles: moveFiles,
            replaceTotal: replaceData.length,
            moveTotal: moveFiles.length,
            total: replaceData.length + moveFiles.length
        }
    }
}
// 递归地获取文件夹中的所有文件路径
const getFilesRecursively = (directory) => {
    const files = []
    const readDirectory = (dir) => {
        const items = fs.readdirSync(dir)
        items.forEach(item => {
            const fullPath = path.join(dir, item)
            const stats = fs.statSync(fullPath)
            if (stats.isDirectory()) {
                readDirectory(fullPath) // 递归读取子目录
            } else {
                files.push(fullPath) // 将文件添加到列表中
            }
        })
    }
    readDirectory(directory)
    return files
}
// 创建一个映射，键是相对于文件夹A的路径，值是文件的绝对路径
const createFilePathMap = (files, baseDir) => {
    const filePathMap = {}
    files.forEach(file => {
        const relativePath = path.relative(baseDir, file)
        filePathMap[relativePath] = file
    })
    return filePathMap
}
// 替换文件
const replaceFilesInDirectory = (directory, filePathMap) => {
    const ReplacedList = []
    const walk = (dir) => {
        const items = fs.readdirSync(dir)
        items.forEach(item => {
            const fullPath = path.join(dir, item)
            const stats = fs.statSync(fullPath)
            if (stats.isDirectory()) {
                walk(fullPath) // 递归遍历子目录
            } else {
                const relativePath = path.relative(directory, fullPath)
                if (filePathMap[relativePath]) {
                    // 如果文件夹A中有相同的文件路径，则替换文件夹B中的文件
                    fs.copyFileSync(filePathMap[relativePath], fullPath)
                    ReplacedList.push(fullPath)
                }
            }
        })
    }
    walk(directory)
    return ReplacedList
}
// 添加文件
const moveFilesIfNotExist = (sourceDir, targetDir) => {
    const moveList = []
    // 确保目标目录存在
    fs.ensureDirSync(targetDir)
    const walk = (dir) => {
        const items = fs.readdirSync(dir)
        items.forEach(item => {
            const sourcePath = path.join(dir, item)
            const stats = fs.statSync(sourcePath)

            if (stats.isDirectory()) {
                // 如果是一个目录，则递归处理
                const targetSubDir = path.join(targetDir, path.relative(sourceDir, sourcePath))
                fs.ensureDirSync(targetSubDir) // 确保目标子目录存在
                walk(sourcePath)
            } else {
                // 如果是一个文件，则检查目标位置是否存在该文件
                const targetPath = path.join(targetDir, path.relative(sourceDir, sourcePath))
                if (!fs.existsSync(targetPath)) {
                    // 如果目标文件不存在，则移动文件
                    fs.moveSync(sourcePath, targetPath, { overwrite: false }) // overwrite: false 防止覆盖现有文件
                    console.log(`Moved ${sourcePath} to ${targetPath}`)
                    moveList.push(sourcePath)
                }
            }
        })
    }
    walk(sourceDir)
    return moveList
}

FsService.toString = () => '[class FsService]'
module.exports = FsService